package linker

import "rvld/src/utils"

func NewSymbol(name string) *Symbol {
	s := &Symbol{
		Name:   name,
		SymIdx: -1,
	}

	return s
}

func (s *Symbol) GetAddr() uint64 {
	if s.SectionFragment != nil {
		return s.SectionFragment.GetAddr() + s.Value
	}

	if s.InputSection != nil {
		return s.InputSection.GetAddr() + s.Value
	}

	return s.Value
}

func (s *Symbol) GetGotTpAddr(ctx *Context) uint64 {
	return ctx.Got.Shdr.Addr + uint64(s.GotTpIdx)*8
}

func (s *Symbol) Clear() {
	s.File = nil
	s.InputSection = nil
	s.SymIdx = -1
}

func (s *Symbol) ElfSym() *Sym {
	utils.ThisAssert(s.SymIdx < len(s.File.ElfSyms))
	return &s.File.ElfSyms[s.SymIdx]
}

func (s *Symbol) SetInputSection(input_section *InputSection) {
	s.InputSection = input_section
	s.SectionFragment = nil
}

func (s *Symbol) SetSectionFragment(sec_frag *SectionFragment) {
	s.InputSection = nil
	s.SectionFragment = sec_frag
}

func GetSymbolByName(ctx *Context, name string) *Symbol {
	if sym, ok := ctx.SymbolMap[name]; ok {
		return sym
	}

	ctx.SymbolMap[name] = NewSymbol(name)
	return ctx.SymbolMap[name]
}

// DONE
